<?php

namespace App\Models;

use App\Exceptions\ApiException;
use App\Exceptions\NotLoginException;
use App\Libraries\rong_cloud_sdk\Rongyun;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class ClientUserTicket extends CommonModel
{
	protected $table = 'client_user_ticket';
	
	/**
	 * @param $uid
	 * @return bool|string
	 * 登录操作，存入ticket
	 */
	public function login($uid){
		$ticket = uuid();
		// 登录就刷新融云token
		$rongyun = new Rongyun();
		$user = DB::table('client_user')->where ('id',$uid)->first();
		$rong = $rongyun->user()->getToken($uid,$user->username,$user->avatar);

		$rong_token = $rong['token'];
		$add = [
			'uid'			=> $uid,
			'session_id'	=> session_id(),
			'ticket'		=> $ticket,
			'rongcloud_token'=> $rong_token,
			'status'		=> 0,
			'ip'			=> request()->ip(),
			'client_system'	=> request('ClientSystem'),
			'client_version'=> request('ClientVersion'),
			'api_version'	=> request('ApiVersion','1.0'),
			'timeout'		=> request()->server('REQUEST_TIME',time()) + 3600 * 3,
		];
		$var = $this->create($add)->id;
		
		// 单点登录，把其他的设置为失效
		static::where('id','!=',$var)->where('uid','=',$uid)->update(['status'=>2]);
		return $var ? $ticket : false;
	}
	
	/**
	 * @param $uid	// 如果传递就全部下线，否则只退出当前ticket
	 * 登出操作，设置状态为已下线
	 */
	public function logout($uid = 0){
		$ticket = request('ticket');
		if($uid){
			$var = $this->where(['uid'=>$uid])->update(['status'=>2]);
		}else{
			$var = $this->where(['ticket'=>$ticket])->update(['status'=>2]);
		}
		return $var;
	}
	
	/**
	 * @param $query
	 * @return mixed
	 * @throws ApiException
	 * 根据ticket查询状态
	 */
	public function checkLogin(){
		$ticket = request('ticket');
		$exist = $this->where(['ticket'=>$ticket])->first();

		if(empty($exist)){
			throw new NotLoginException('未检测到用户凭证');
		}elseif($exist->status == 2){
			throw new NotLoginException('登录已失效，请重新登录');
		}elseif($exist->status == 0){
			$user = ClientUser::select(DB::raw('id,username,realname,mobile,email,password,salt,gender,avatar,signature,type,created_at'))->where(['id'=>$exist->uid])->first();
			return $user;
		}else{
			throw new NotLoginException('用户凭证数据状态无效');
		}
	}
}
